package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmSensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmSensitiveImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {

    @Override
    public ResponseResult findAll(WmSensitiveDto dto) {

        //1.检查分页参数
        dto.checkParam();

        //2.分页查询
        Page page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(WmSensitive::getSensitives,dto.getName());
        }

        queryWrapper.orderByDesc(WmSensitive::getCreatedTime);

        page = page(page, queryWrapper);

        if (page.getRecords() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult saveSensitive(WmSensitive wmSensitive) {
        if (StringUtils.isEmpty(wmSensitive.getSensitives())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmSensitive.setCreatedTime(new Date());
        save(wmSensitive);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult deleteById(int id) {
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateSensitive(WmSensitive wmSensitive) {
        update(Wrappers.<WmSensitive>lambdaUpdate().eq(WmSensitive::getId,wmSensitive.getId())
                .set(WmSensitive::getSensitives,wmSensitive.getSensitives())
                .set(WmSensitive::getCreatedTime,new Date()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
